<template>
	<view class="coupon-page">
		<!-- 1. 顶部导航栏 -->
		<view class="custom-nav">
			<view class="nav-item" v-for="(item, index) in navList" :key="index"
				:class="{ 'active': activeNav === index }" @click="loadCoupons(index)">
				{{ item }}
			</view>
		</view>

		<view class="coupon-center" @click="goToCouponCenter">
			<text>领券中心</text>
		</view>

		<!-- 2. 优惠券列表 -->
		<view class="coupon-list">
			<!-- 单个优惠券卡片 -->
			<view class="coupon-card" v-for="(item, index) in couponList" :key="index">
				<!-- 快过期角标 -->
				<view class="expired-tag" v-if="item.isExpired">快过期</view>
				<view v-if="!item.isAvailable" class="unavailable-reason">
					{{ item.unavailableReason }}
				</view>
				<!-- 内容容器：左金额 + 右信息 -->
				<view class="coupon-content">
					<!-- 左侧金额区域 -->
					<view class="amount-wrap">
						<text class="amount">¥{{item.discount}}</text>
						<text class="condition">满{{item.min}}可用</text>
					</view>
					<!-- 右侧信息区域 -->
					<view class="info-wrap">
						
						<text class="limit-text">{{item.limitText}}</text>
						<text class="countdown">有效期限{{item.startTime}} - {{item.endTime}}</text>
						<!-- <button class="use-btn" :class="{ 'disabled': !item.isAvailable }" @click="selectCoupon(item)"
							:disabled="!item.isAvailable">
							{{ item.isSelected ? '已选择' : '立即使用' }}
						</button> -->
						<button class="use-btn" :class="{ 
						  'disabled': !item.isAvailable,
						  'selected': item.isSelected
						}" @click="selectCoupon(item)"
								:disabled="!item.isAvailable">
							{{ item.isSelected ? '已选择' : '立即使用' }}
						</button>
					</view>
				</view>
			</view>

			<!-- 无优惠券提示（可选） -->
			<view class="empty-tip" v-if="couponList.length === 0">
				暂无可用优惠券~
			</view>
		</view>

		<!-- 3. 底部说明（可选） -->
		<view class="footer-tip">
			<text>优惠券使用规则：满减券需满足金额条件，限指定商品可用</text>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import {
		getCouponList,
		checkCouponAvailability
	} from '@/config/api/coupon.js';
	export default {
		data() {
			return {
				navList: ['全部', '即将过期', '已使用', '已过期'],
				activeNav: 0,
				couponList: [],
				sumPrice: 0, // 接收订单总金额
				isFromOrderPage: false, // 是否从订单页面进入
				goodsList: [], // 订单商品列表
				selectedCoupon: null,
			};
		},

		computed: {
			...mapState(['userInfo'])
		},
		mounted() {
			this.loadCoupons()
		},
		onLoad(options) {
			// 接收订单总金额
			console.log('接收的订单金额:', options.sumPrice); // 添加日志
			if (options.sumPrice) {
				this.sumPrice = parseFloat(options.sumPrice) || 0;
				this.isFromOrderPage = true; // 标记来自订单页面
			} else {
				this.isFromOrderPage = false; // 标记直接进入
			}
			if (options.selectedCoupon) {
			    try {
			      this.selectedCoupon = JSON.parse(options.selectedCoupon);
			    } catch (e) {
			      console.error("解析selectedCoupon失败", e);
			    }
			  }
			  
			  if (options.goodsList) {
			    try {
			      this.goodsList = JSON.parse(options.goodsList);
			    } catch (e) {
			      console.error("解析goodsList失败", e);
			    }
			  }
			
			this.loadCoupons();
		},
		onShow(){
			this.loadCoupons();
		},
		methods: {
			async loadCoupons(index = this.activeNav) {
				if (index !== undefined) {
					this.activeNav = index; // 更新当前激活的导航索引
				}
				const userId = this.userInfo.id;
				let status = index;
				if (index === 1) { // 即将过期
					status = 0;
				} else if (index >= 2) { // 已过期和已使用
					status = index - 1;
				}
				console.log(status);
				
				// if (res.data.code === 200) {
				// 	this.couponList = await Promise.all(
				// 	  res.data.data.map(async item => {
				// 		// 校验优惠券可用性
				// 		const { isAvailable, reason } = await this.checkCouponAvailability(item);
						
				// 		return {
				// 		  ...item,
				// 		  isAvailable,
				// 		  unavailableReason: reason,
				// 		  isSelected: this.selectedCoupon?.id === item.id
				// 		};
				// 	  })
				// 	);
				//   }
				
				
				try {
					const res = await getCouponList({
						userId,
						status
					});
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						// this.couponList = res.data.data.map(item => {
						// 	const isAvailable = this.isFromOrderPage ?
						// 		this.sumPrice >= item.min :
						// 		true; // 直接进入时默认可用
						// 	const isSelected = this.selectedCoupon && this.selectedCoupon.id === item.id;
						// 	return {
						// 		...item,
						// 		isAvailable,
						// 		isSelected	
						// 	};
						// });
						// console.log(this.couponList);
						const coupons = await Promise.all(
							res.data.data.map(async item => {
								// 校验优惠券可用性
								const availability = await this.checkCouponAvailability(item);
								
								return {
									...item,
									...availability,
									isSelected: this.selectedCoupon?.id === item.id
								};
							})
						);
						this.couponList = coupons;
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.couponList = []; // 清空列表
					this.$message.error('数据加载失败')
				}

			},


			// 校验优惠券可用性
			async checkCouponAvailability(coupon) {
				// 如果不是从订单页面进入，默认可用
				// if (!this.isFromOrderPage) {
				// 	return {
				// 		isAvailable: true,
				// 		unavailableReason: ''
				// 	};
				// }
				if (!this.isFromOrderPage) {
				    return { isAvailable: true, unavailableReason: '' };
				  }
				// 1. 检查金额条件
				if (this.sumPrice < coupon.min) {
					return {
						isAvailable: false,
						unavailableReason: `未满足最低消费¥${coupon.min}`
					};
				}
				// JSON.stringify(this.goodsList)
				// 2. 检查商品范围
				if (coupon.goodsType !== 0 && this.goodsList.length > 0) {
				    try {
				      const res = await checkCouponAvailability({
				        couponId: coupon.id,
				        goodsList: JSON.stringify(this.goodsList)
				      });
				      
				      if (res?.data?.code === 200) {
				        if (!res.data.data.isValid) {
				          return {
				            isAvailable: false,
				            unavailableReason: res.data.data.reason || '不在使用范围'
				          };
				        }
				      } else {
				        return {
				          isAvailable: false,
				          unavailableReason: '校验失败'
				        };
				      }
				    } catch (error) {
				      console.error('校验优惠券失败:', error);
				      return {
				        isAvailable: false,
				        unavailableReason: '校验失败'
				      };
				    }
				  }
				  
				  return {
				    isAvailable: true,
				    unavailableReason: ''
				  };
			},
			
			// 选择优惠券
			selectCoupon(item) {
				// 如果是直接进入，提示用户
				if (!this.isFromOrderPage) {
					uni.switchTab({
						url: '/pages/index/index'
					});
					return;
				}

				if (!item.isAvailable) return;

				// 标记选中状态
				this.couponList = this.couponList.map(c => ({
					...c,
					isSelected: c.id === item.id
				}));

				// 使用全局事件代替事件通道
				uni.$emit('couponSelected', item);
				console.log('通过全局事件发送优惠券:', item);


				uni.showToast({
					title: '优惠券已选择',
					icon: 'success'
				});

				// 1秒后自动返回
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			},
			// 前往领券中心页面
			goToCouponCenter() {
				uni.navigateTo({
					url: '/pages/user/linCoupon' // 请根据实际路径修改
				});
			}
		}
	};
</script>

<style scoped>
	/* 页面容器 */
	.coupon-page {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 自定义导航栏 */
	.custom-nav {
		background-color: #fff;
		display: flex;
		justify-content: space-around;
		padding: 16px;
	}

	.nav-item {
		font-size: 16px;
		color: #000;
		cursor: pointer;
	}

	.nav-item.active {
		border-bottom: 2px solid #fff;
	}

	.coupon-center {
		background-color: #fff;
		padding: 16px;
		text-align: center;
		font-size: 16px;
		color: #ff4d4f;
		cursor: pointer;
		border-top: 1px solid #eee;
		border-bottom: 1px solid #eee;
	}

	/* 添加不可用原因样式 */
		.unavailable-reason {
			position: absolute;
			top: 8px;
			right: 8px;
			padding: 4px 8px;
			background-color: #ff4d4f;
			color: white;
			font-size: 12px;
			border-radius: 4px;
			z-index: 1;
		}
		
		/* 添加选中状态样式 */
		.use-btn.selected {
			background-color: #52c41a !important;
		}
	
	/* 优惠券列表 */
	.coupon-list {
		padding: 16px;
		flex: 1;
		/* 占满剩余空间，让底部固定 */
	}

	/* 单个优惠券卡片 */
	.coupon-card {
		position: relative;
		/* 角标绝对定位用 */
		display: flex;
		align-items: flex-start;
		background: #fff;
		border-radius: 8px;
		padding: 12px 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
		margin-bottom: 16px;
	}

	/* 快过期角标 */
	.expired-tag {
		position: absolute;
		top: 8px;
		left: 0;
		padding: 4px 8px;
		background: #ff4d4f;
		color: #fff;
		font-size: 12px;
		border-radius: 0 4px 4px 0;
		z-index: 1;
	}

	/* 内容容器：左右布局 */
	.coupon-content {
		display: flex;
		align-items: center;
		width: 100%;
	}

	/* 左侧金额区域 */
	.amount-wrap {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		margin-right: 16px;
	}

	.amount {
		font-size: 30px;
		font-weight: bold;
		color: #ff4d4f;
		line-height: 1.2;
	}

	.condition {
		font-size: 14px;
		color: #ff4d4f;
		margin-top: 4px;
	}

	/* 右侧信息区域 */
	.info-wrap {
		display: flex;
		flex-direction: column;
		justify-content: center;
		flex: 1;
	}

	.limit-text {
		font-size: 16px;
		color: #333;
		padding-top: 20px;
		line-height: 1.4;
	}

	.countdown {
		font-size: 12px;
		color: #ff4d4f;
	}

	/* 立即使用按钮 */
	.use-btn {
		align-self: flex-start;
		background-color: #ff4d4f;
		color: #fff;
		font-size: 14px;
		margin-right: 5px;
		border-radius: 4px;
		border: none;
		min-width: 80px;
		height: 30px;
		line-height: 30px;
		text-align: center;
	}

	/* 添加禁用状态样式 */
	.use-btn.disabled {
		background-color: #ccc !important;
		cursor: not-allowed;
	}

	.use-btn:active {
		opacity: 0.8;
	}

	/* 无优惠券提示 */
	.empty-tip {
		text-align: center;
		color: #999;
		font-size: 14px;
		margin-top: 40px;
	}

	/* 底部说明 */
	.footer-tip {
		padding: 12px 16px;
		background-color: #fff;
		border-top: 1px solid #eee;
	}

	.footer-tip text {
		font-size: 12px;
		color: #999;
	}
</style>